<template>
  <div class="c-p" :class="!hasCommentList && positionType == 'detail' ? '' : 'c-minh640'">
    <div v-if="enableShowComment == 0 && isShowCommentTip && (hasCommentList || (!hasCommentList && positionType != 'detail'))" class="c-w100 c-hh60 c-p c-flex-row c-flex-center">
      <div class="c-w100 c-h theme-bg c-opacity10"></div>
      <div class="c-pa c-p-t0 c-p-l0 theme-fc c-fs22 c-w100 c-h c-flex-row c-flex-center"><span class="iconfont c-pr10">&#xe963;</span>评论经后台审核后展示</div>
    </div>
    <div class="c-ph24 " :class="is_onePage ? 'c-bd-dd1' : ''" v-if="commentList1 && commentList1.length > 0">
      <h1 :class="smallText ? 'c-fs20' : 'c-fs24'" class="c-fw600 c-fc-xblack c-pv40">
        <span>精品评论</span>
      </h1>
      <div class="c-flex-column c-pb24" :class="index == (commentList1.length -1) ? '' : 'c-bd-b1 c-mb24'" v-for="(item,index) in commentList1" :key="index">
        <div class="c-flex-row">
          <img v-lazy="item.headimgurl || require('@/assets/defult_head.png')" @click="handleClickPlaint()" :key="item.headimgurl" class="c-ww60 c-hh60 c-brp50 c-mr16 c-block" />
          <div class="c-flex-column c-flex-grow1 c-justify-sb">
            <div class="c-fs22 c-fc-blue">{{item.nickname != null && item.nickname != '' ? nameLength(item.nickname, 2) : '未知用户'}}</div>
            <div :class="item.status == 1 ? 'c-fc-xblack' : 'c-fc-gray'" @click="addComment(item, index, 1)" class="c-pv12 c-fs24 wrap c-lh36">
              {{item.status == 1 ? item.content : '该评论已被隐藏，无法查看'}}
            </div>
            <div @click="addComment(item, index, 1)" class="c-pt12 c-pb20 c-fs20 c-flex-row c-aligni-center">
              <div class="c-fc-gray">{{item.createdAt}}</div>
              <div class="c-fc-xblack c-ml20">回复</div>
            </div>
            <div class="c-ph20 c-pv4 c-bg-fafafa c-br20" v-if="item.replyList && item.replyList.length > 0">
              <div :class="rindex == (item.replyList.length - 1) ? '' : 'c-bd-b1'" class="c-pv20 c-fs22 c-fc-xblack wrap" @click="addComment(ritem, index, 1)" v-show="item.isTotalShow == false ? (rindex < 3) : (rindex >= 0)" v-for="(ritem,rindex) in item.replyList" :key="rindex">
                <div><span :class="ritem.type == 3 && ritem.userId == 0 ? 'c-fc-mred' : 'c-fc-blue'">{{ritem.type == 3 && ritem.userId == 0 ? '管理员' : ritem.nickname ? nameLength(ritem.nickname, 2) : '未知用户'}}</span><span class="c-fc-gray" v-if="ritem.parentCId != item.cId"> 回复 </span><span :class="ritem.parentUserId == 0 ? 'c-fc-mred' : 'c-fc-blue'" v-if="ritem.parentCId != item.cId">{{ritem.parentUserId == 0 ? '管理员' : ritem.parentName ? nameLength(ritem.parentName, 2) : '未知用户'}}</span></div>
                <div class="c-mt12 c-lh36"><span :class="ritem.status == 1 ? '' : 'c-fc-gray'">{{ritem.status == 1 ? ritem.content : '该评论已被隐藏，无法查看'}}</span></div>
                <div class="c-mt12 c-fs20 c-flex-row c-aligni-center">
                  <div class="c-fc-gray">{{ritem.createdAt}}</div>
                  <div class="c-fc-xblack c-ml20">回复</div>
                </div>
              </div>
              <div v-if="item.replyList && item.replyList.length > 3 && item.isTotalShow == false" @click="item.isTotalShow = true" class="c-fs22 c-fc-smblue c-pv8">查看全部 {{item.replyList.length}} 条回复</div>
            </div>
          </div>
        </div>
      </div>
      <div class="c-fs22 c-fc-xblack c-pv30 c-textAlign-c" v-if="is_onePage" @click="getJPComments(1)">加载更多&nbsp;></div>
    </div>
    <div class="c-ph24" v-if="commentList2 && commentList2.length > 0">
      <h1 :class="smallText ? 'c-fs20' : 'c-fs24'" class="c-fw600 c-fc-xblack c-pv40">
        <span>最新评论</span>
      </h1>
      <div class="c-flex-column c-pb24" :class="index == (commentList2.length -1) ? '' : 'c-bd-b1 c-mb24'" v-for="(item,index) in commentList2" :key="index">
        <div class="c-flex-row">
          <img v-lazy="item.headimgurl || require('@/assets/defult_head.png')" :key="item.headimgurl" @click="handleClickPlaint()" class="c-ww60 c-hh60 c-brp50 c-mr16 c-block" />
          <div class="c-flex-column c-flex-grow1 c-justify-sb">
            <div class="c-fs22 c-fc-blue">{{item.nickname != null && item.nickname != '' ? nameLength(item.nickname, 2) : '未知用户'}}</div>
            <div :class="item.status == 1 ? 'c-fc-xblack' : 'c-fc-gray'" @click="addComment(item, index, 0)" class="c-pv12 c-fs24 wrap c-lh36">
              {{item.status == 1 ? item.content : '该评论已被隐藏，无法查看'}}
            </div>
            <div v-if="replyPermission" @click="addComment(item, index, 0)" class="c-pt12 c-pb20 c-fs20 c-fc-sgray c-flex-row c-aligni-center">
              <div class="c-fc-gray">{{item.createdAt}}</div>
              <div class="c-fc-xblack c-ml20">回复</div>
            </div>
            <div class="c-ph20 c-pv4 c-bg-fafafa c-br20" v-if="item.replyList && item.replyList.length > 0">
              <div :class="rindex == (item.replyList.length - 1) ? '' : 'c-bd-b1'" class="c-pv20 c-fs22 c-fc-xblack wrap" @click="addComment(ritem, index, 0)" v-show="item.isTotalShow == false ? (rindex < 3) : (rindex >= 0)" v-for="(ritem,rindex) in item.replyList" :key="rindex">
                <div><span :class="ritem.type == 3 && ritem.userId == 0 ? 'c-fc-mred' : 'c-fc-blue'">{{ritem.type == 3 && ritem.userId == 0 ? '管理员' : ritem.nickname ? nameLength(ritem.nickname, 2) : '未知用户'}}</span><span class="c-fc-gray" v-if="ritem.parentCId != item.cId"> 回复 </span><span :class="ritem.parentUserId == 0 ? 'c-fc-mred' : 'c-fc-blue'" v-if="ritem.parentCId != item.cId">{{ritem.parentUserId == 0 ? '管理员' : ritem.parentName ? nameLength(ritem.parentName, 2) : '未知用户'}}</span></div>
                <div class="c-mt12 c-lh36"><span :class="ritem.status == 1 ? '' : 'c-fc-gray'">{{ritem.status == 1 ? ritem.content : '该评论已被隐藏，无法查看'}}</span></div>
                <div class="c-mt12 c-fs20 c-fc-sgray c-flex-row c-aligni-center">
                  <div class="c-fc-gray">{{ritem.createdAt}}</div>
                  <div v-if="replyPermission" class="c-fc-xblack c-ml20">回复</div>
                </div>
              </div>
              <div v-if="item.replyList && item.replyList.length > 3 && item.isTotalShow == false" @click="item.isTotalShow = true" class="c-fs22 c-fc-smblue c-pv8">查看全部 {{item.replyList.length}} 条回复</div>
            </div>
          </div>
        </div>
      </div>
      <div class="c-fs22 c-fc-xblack c-pv30 c-textAlign-c" v-if="is_page" @click="getComments(1)">加载更多&nbsp;></div>
    </div>
    <loading-status-tem v-show="positionType != 'detail'" noDataStyle="padding: 0px" :class="commentList1.length == 0 && commentList2.length == 0 ? 'c-bg-white c-hh640 c-flex-column c-flex-center' : ''" :noData="commentList1.length == 0 && commentList2.length == 0" :noDataText="'暂无评论'"></loading-status-tem>
    <div v-if="showAddComment">
      <div @click="showAddComment = false;commentMsg='';" class="c-pf c-p-r0 c-p-l0 c-p-t0 c-p-b0 c-translucent-balck60 c-pz1000"></div>
      <div class="c-pf c-bg-white c-p-b0 c-w100 c-maxw640 c-pz6 c-pv20 c-box-shadow7 c-pz1002 c-br-tl16 c-br-tr16">
        <div class="c-fs24 c-fw400 c-ph20 c-fc-gray c-text-ellipsis1">{{this.isAdd ? '添加评论：' : '回复' + (this.commentUser.userId == 0 ? '管理员' : nameLength(this.commentUser.nickname, 2)) + '：' + (this.commentUser.status == 1 ? this.commentUser.content : '该评论已被隐藏，无法查看')}}</div>
        <div class="c-bg-white c-mt12 c-ph20 c-pb24 c-bd-b1-f5">
          <textarea ref="commentInput" autofocus="autofocus" v-model="commentMsg" rows="3" class="c-fs24 c-bg-white c-bd0 c-w100 c-fs24 c-lh40" placeholder="说点什么吧～"></textarea>
        </div>
        <div class="c-flex-row c-aligni-center c-justify-end c-pt24 c-ph20">
          <div class="c-fs22 c-fc-sgray">({{commentMsg.length}}/1000)</div>
          <div @click="onConfirm" class="c-fs22 c-fc-white c-hh48 c-lh50 c-ww120 c-textAlign-c theme-bg c-br36 c-ml20">发送</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
let commentChangeArr = [];
let goodCommentChangeArr = [];
let toPop = false;
export default {
  name: 'Comment',
  components: {
    loadingStatusTem
  },
  props: {
    prodType: {
      type: String,
      default: ''
    },
    prodId: {
      type: String,
      default: ''
    },
    moduleType: {
      type: Number,
      default: 1
    },
    bindPhoneSetting: {
      type: Object,
      default: () => {}
    },
    isShowCommentTip: {
      type: Boolean,
      default: true
    },
    smallText: {
      type: Boolean,
      default: false
    },
    replyPermission: {
      type: Boolean,
      default: true
    },
    positionType: { // 当前评论模块放的位置,详情页的评论tab下还是详情tab（detail）下
      type: String,
      default: 'tab'
    },
  },
  beforeCreate() {

  },
  data() {
    return {
      cfg: JSON.parse(localStorage.getItem("cfg")), //enableShowComment 评论开关 1显示，0隐藏,
      cfrom: global.ckFrom,
      onePage: 1,
      is_onePage: false,
      commentList1: [],
      commentList2: [],
      tmp_page: 1,
      tmp_page_one: 1,
      is_page: false,
      limit: 10,
      page: 1,
      isGood: false,
      commentStatus: 0,
      cIndex: -1,
      isAdd: false,
      showAddComment: false,
      commentMsg: '',
      commentUser: '',
    }
  },
  created() {

  },
  mounted() {
  },
  computed: {
    // 管理端，全局设置默认隐藏cfg.enableShowComment=0，课程、打卡、专栏、知识套餐、训练营、电子书中的评论需通过管理员在【用户管理-用户评论】页设置为显示后，方可对所有用户显示
    enableShowComment() {
      const prodList = [
        this.cfrom.course,
        this.cfrom.clockIn,
        this.cfrom.column,
        this.cfrom.package,
        this.cfrom.camp,
        this.cfrom.ebooks,
      ]
      return !prodList.includes(Number(this.prodType)) ? true : this.cfg.enableShowComment != 0
    },
    hasCommentList() {
      return this.commentList1 && this.commentList1.length && this.commentList2 && this.commentList2.length
    }
  },
  watch: {},
  methods: {
    getCommentCount() {
      let getUrl = `${global.apiurl}comments/count?moduleType=${this.moduleType}&prodId=${this.prodId}&prodType=${this.prodType}`;
      utilJs.getMethod(getUrl, res => {
        this.$emit('getCommentCount', res || 0)
      })
    },
    //评论
    addComment(commentUser = '', index = 0, isGood = false) {
      if (!this.replyPermission) {
        return
      }
      if (this.bindPhoneSetting && this.bindPhoneSetting.commentBind && utilJs.goBindMobile()) {
        return;
      }
      this.commentMsg = "";
      this.commentUser = commentUser;
      this.cIndex = index;
      this.isGood = Number(isGood) == 1 ? true : false;
      this.isAdd = commentUser ? false : true;
      this.showAddComment = true;
      this.$nextTick(() => {
        this.$refs.commentInput.focus();
      })
    },
    commentChange: function(commentArr, parentName, commentType, parentUserId) {
      for (let i = 0; i < commentArr.length;i++) {
        commentArr[i].parentName = parentName;
        commentArr[i].parentUserId = parentUserId;
        commentArr[i].createdAt = utilJs.changeCommentTime(commentArr[i].createdAt);
        if (commentType == 1) {
          commentChangeArr.push(commentArr[i]);
        } else if (commentType == 2) {
          goodCommentChangeArr.push(commentArr[i]);
        }
        if (commentArr[i].items && commentArr[i].items.length > 0) {
          this.commentChange(commentArr[i].items, commentArr[i].nickname, commentType, commentArr[i].userId)
        }
      }
    },
    // 接口已经有过滤了？
    filterCommentList(list = []) { // isFriend == 0 为黑名单，前端需要过滤
      list.forEach(item => {
        if (item.replyList && item.replyList.length > 0) {
          item.replyList = item.replyList.filter(i => i.isFriend != 0)
        }
      })
      return list
    },
    getJPComments(getType) {
      if (getType == 2) {
        this.onePage = parseInt(this.cIndex / 10) + 1;
      }
      const postUrl = `${global.apiurl}comments?moduleType=${this.moduleType}&isGood=1&prodId=${this.prodId}&prodType=${this.prodType}&page=${this.onePage}&limit=${this.limit}`;
      utilJs.getMethod(postUrl, res => {
        const resData = this.filterCommentList(res || []);
        goodCommentChangeArr = [];
        resData.forEach(item => {
          item.isTotalShow = false;
          item.createdAt = utilJs.changeCommentTime(item.createdAt);
          if (item.items && item.items.length > 0) {
            this.commentChange(item.items, item.nickname, 2, item.userId)
            item.replyList = goodCommentChangeArr;
            goodCommentChangeArr = [];
          }
        })
        if (getType == 1) {
          this.commentList1 = [...this.commentList1, ...resData]
        }
        if (getType == 2 && this.isAdd) {
          this.commentList1.unshift(resData[0]);
          if (resData.length >= this.limit) {
            this.commentList1.pop();
          }
          this.onePage = this.tmp_page_one;
        } else if (getType == 2 && !this.isAdd) {
          this.$set(this.commentList1, this.cIndex, resData[this.cIndex % 10]);
          this.onePage = this.tmp_page_one;
        }
        this.tmp_page_one = this.onePage;
        this.onePage = resData && (resData.length >= this.limit) ? (this.onePage + 1) : this.onePage;
        this.is_onePage = resData && (resData.length >= this.limit) ? true : false;
      });
    },
    //获取评论
    getComments(getType) {
      if (getType == 2) {
        this.page = parseInt(this.cIndex / 10) + 1;
      }
      let postUrl = `${global.apiurl}comments?moduleType=${this.moduleType}&isGood=0&prodId=${this.prodId}&prodType=${this.prodType}&page=${this.page}&limit=${this.limit}`;
      utilJs.getMethod(postUrl, res => {
        const resData = this.filterCommentList(res || []);
        commentChangeArr = [];
        resData.forEach(item => {
          item.isTotalShow = false;
          item.createdAt = utilJs.changeCommentTime(item.createdAt);
          if (item.items && item.items.length > 0) {
            this.commentChange(item.items, item.nickname, 1, item.userId)
            item.replyList = commentChangeArr;
            commentChangeArr = [];
          }
        })
        if (getType == 1) {
          this.commentList2 = [...this.commentList2, ...resData]
        }
        if (getType == 2 && this.isAdd && this.enableShowComment) {
          this.commentList2.unshift(resData[0]);
          if (toPop) {
            toPop = false;
            this.commentList2.pop();
          }
          if (resData.length >= this.limit) {
            toPop = true;
          }
          this.page = this.tmp_page;
        } else if (getType == 2 && !this.isAdd) {
          this.$set(this.commentList2, this.cIndex, resData[this.cIndex % 10]);
          this.page = this.tmp_page;
        }
        this.tmp_page = this.page;
        this.page = resData && (resData.length >= this.limit) ? (this.page + 1) : this.page;
        this.is_page = resData && (resData.length >= this.limit) ? true : false;
      }
      );
    },
    handleClickPlaint() {
      this.$emit('handleClickPlaint')
    },
    nameLength(name, length) {
      return utilJs.nameLength(name, length)
    },
    onConfirm: function () {
      if (!(this.commentMsg && this.commentMsg.length && this.commentMsg.trim() != '')) {
        this.$showCjToast({
          text: "评论长度至少1个字符",
          type: "warn"
        });
        return
      }
      if (this.commentMsg.length > 1000) {
        this.$showCjToast({
          text: '评论内容不能超过1000字！',
          type: 'warn'
        });
        return;
      }
      let data = {
        moduleType: this.moduleType,
        type: this.isAdd ? 1 : 2,
        parentCId: this.commentUser ? this.commentUser.cId : 0,
        prodId: this.prodId,
        prodType: this.prodType,
        content: this.commentMsg,
        rootCId: this.commentUser ? this.commentUser.rootCId : 0,
        status: this.enableShowComment,
      };
      utilJs.postMethod(global.apiurl + "comments", data, res => {
        if (res.isBan == 1) {
          this.$cjConfirm({
            showCancelButton: false,
            title: '温馨提示',
            message: `暂无权限评论，请联系管理员~`,
          });
          return
        }
        if (this.isGood) {
          this.getJPComments(2);
        } else {
          this.getComments(2);
        }
        this.commentMsg = '';
        this.getCommentCount()
        this.$showCjToast({
          text: "评论成功",
          type: "success"
        });
        this.$emit('addCommentSuccess')
      });
      this.showAddComment = false;
    },
    public_initData() {
      this.onePage = 1;
      this.is_onePage = false;
      this.commentList1 = [];
      this.commentList2 = [];
      this.tmp_page = 1;
      this.tmp_page_one = 1;
      this.is_page = false;
      this.limit = 10;
      this.page = 1;
      this.isGood = false;
      this.commentStatus = 0;
      this.cIndex = -1;
      this.isAdd = false;
      this.showAddComment = false;
      this.commentMsg = '';
      this.commentUser = '';
      this.getCommentCount()
      this.getJPComments(1);
      this.getComments(1)
    },
    public_addComment() {
      this.addComment()
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wrap {
  white-space: normal;
  word-break: break-all;
}
</style>
